package com.guguguweb.rpc.codec;

import com.guguguweb.rpc.entity.RpcRequest;
import com.guguguweb.rpc.enumeration.PackageType;
import com.guguguweb.rpc.serializer.CommonSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


//消息的定义为 ：消息头 + 消息体
//消息头：MAGIC_NUMBER + 本次请求类型 + 序列化器的编号 + 消息体的长度
//消息体：即为 发送的Java序列化之后的字节数组


/**
 * netty的通用message解码器，将对象转化成字节数组
 */
public class MessageEncoder extends MessageToByteEncoder {


    private static final Logger log = LoggerFactory.getLogger(MessageEncoder.class);

    private static final int MAGIC_NUMBER = 0x666ABC;

    private final CommonSerializer serializer;

    public MessageEncoder(CommonSerializer serializer){
        this.serializer = serializer;
    }

    @Override
    public void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf out) throws Exception {
        log.debug("写入的对象是：{} ,类型是 :{}",msg,msg.getClass().getSimpleName());
        out.writeInt(MAGIC_NUMBER);
        if(msg instanceof RpcRequest){
            out.writeInt(PackageType.REQUEST_PACK.getCode());
        }else {
            out.writeInt(PackageType.RESPONSE_PACK.getCode());
        }
        out.writeInt(serializer.getCode());
        byte[] data = serializer.serialize(msg);
        out.writeInt(data.length);
        out.writeBytes(data);
    }
}
